<template>
  <div id="cesium-viewer">
    <slot />
    <div class="btns">
      <p @click="handleNavigate"><i class="iconfont icon-daohang"></i></p>
      <p @click="handleLayer"><i class="iconfont icon-tucengguanli"></i></p>
    </div>
    <div class="layers" v-if="show">
      <div class="layer"><input type="checkbox" v-model="isChecked" /><span class="right">全选</span></div>
      <div class="layer" v-for="item in layers">
        <div
          class="left"
          @click="handCheak(item.name, item.isShow)"
          :style="{ backgroundColor: item.isShow ? item.color : 'transparent', borderColor: item.color }"
        ></div>
        <div class="right">{{ item.name.slice(4, 7) }}</div>
      </div>
    </div>
    <div class="position" v-if="isPositon">
      <p>纬度:{{ lngPosition }}</p>
      <p>经度:{{ latPosition }}</p>
      <p>高度:{{ heightPosition }}</p>
    </div>
  </div>
</template>

<script setup>
import * as Cesium from 'cesium';
import { onMounted, markRaw, ref, watch } from 'vue';
import {
  initViewer,
  setScene,
  loadTilesets,
  handleDefaultModelEffect,
  flyToDefaultView,
  handleUpdateScene,
  addRiver,
} from '@/cesiumTools/sceneManager';
import {
  useLineData,
  renderAll,
  renderStationBill,
  removeAll,
  removeAllBillboards,
  removeAllStations,
  hideLineByName,
  hideStationByName,
} from '@/store';
import { changeStations } from '@/store/staticData.js';
import { getLine } from '@/api/line.js';
import PositionTransfer from '@/cesiumTools/utils';
const isPositon = ref(false);
let lineData = [];
let viewer = null;
const layers = ref([]);
const show = ref(false);
const isChecked = ref(true);
const lineDataStore = useLineData();
const lngPosition = ref('');
const latPosition = ref('');
const heightPosition = ref('');
//初始化cesium实例
Cesium.Ion.defaultAccessToken =
  'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI3ODAzN2EzOS1kZDMzLTQ5Y2UtYjYxMi1jMzQxNTdiMTUzN2IiLCJpZCI6NDU5NDIsImlhdCI6MTYxNTYyNDQyOX0.BucgmI6OJ-7ixj7rcQ_Qyg45DkvdHmaLrFwyMYitLcI';

//切换图层
const handleLayer = () => {
  show.value = !show.value;
};
const handCheak = (name, key) => {
  const is = key ? false : true;
  layers.value.forEach(item => {
    if (item.name === name) {
      item.isShow = is;
      const { stationsList } = item;
      stationsList.forEach(station => {
        hideStationByName(station.name, is);
      });
    }
  });
  hideLineByName(name, is);
};
//坐标导航
const handleNavigate = () => {
  isPositon.value = !isPositon.value;
};
onMounted(async () => {
  viewer = initViewer('cesium-viewer');
  viewer.scene.sun = new Cesium.Sun();
  setScene(viewer);
  flyToDefaultView(viewer);
  const modelUrls = [
    {
      url: 'http://localhost:8888/wuhan/tileset.json',
      options: {},
    },
  ];
  lineDataStore.setViewer(markRaw(viewer));
  // 加载线路数据
  lineData = await getLine();
  lineDataStore.setData(markRaw(lineData));
  // 加载多个3dtiles
  await loadTilesets(viewer, modelUrls, async tilesets => {
    handleDefaultModelEffect(tilesets[0]);
    lineDataStore.setTileset(markRaw(tilesets[0]));
    const waterPrimitive = await addRiver(viewer);
    // 实现早晚变化效果
    handleUpdateScene(viewer, tilesets[0], waterPrimitive);
  });
  renderAll(viewer, lineData);
  const arr = [];
  lineData.forEach(item => {
    const { color, stationsList } = item;
    layers.value.push(item);
    stationsList.forEach(station => {
      const { position, name } = station;
      if (changeStations.includes(name)) {
        //station.color = '#e10602'
        arr.push(station);
        return;
      }
      renderStationBill(viewer, {
        position: position,
        name,
        color: station.color ? station.color : color,
      });
    });
  });
  //去除重复站点
  const newArr = arr.filter((item, index) => {
    return arr.findIndex(i => i.name === item.name) === index;
  });
  newArr.forEach(item => {
    const { position, name } = item;
    const color = '#e10602';
    renderStationBill(viewer, {
      position: position,
      name,
      color: color,
    });
  });
  //监听坐标
  const positionTool = new PositionTransfer(viewer);
  const move = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  move.setInputAction(e => {
    //可以从e中获取到当前点击的屏幕坐标
    const { startPosition } = e;
    //1.将屏幕坐标转为笛卡尔坐标
    const cartesian = positionTool.screenToCartesian3(startPosition);
    if (!cartesian) {
      // console.error('Invalid Cartesian3 object');
      return;
    }
    //2.将笛卡尔坐标转为经纬度坐标
    const { lng, lat, height } = positionTool.cartesion3ToLng(cartesian);
    //console.log(lng,lat,height)
    lngPosition.value = lng.toFixed(4);
    latPosition.value = lat.toFixed(4);
    heightPosition.value = height.toFixed(4);
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
  layers.value.forEach(item => {
    item.isShow = true;
  });
});
watch(isChecked, val => {
  if (val) {
    renderAll(viewer, lineData);
    layers.value.forEach(item => {
      item[2] = true;
    });
    lineData.forEach(item => {
      const { color, stationsList } = item;
      stationsList.forEach(station => {
        const { position, name } = station;
        renderStationBill(viewer, {
          position: position,
          name,
          color,
        });
      });
    });
  } else {
    //移除所有线路
    removeAll(viewer);
    //移除所有站点
    removeAllStations(viewer);
    //移除所有站牌
    removeAllBillboards();
    layers.value.forEach(item => {
      item[2] = false;
    });
  }
});
</script>

<style lang="scss" scoped>
#cesium-viewer {
  width: 100%;
  height: 100%;
  pointer-events: all;
}
.btns {
  position: absolute;
  top: 75%;
  right: 28%;
  color: white;
  z-index: 999;
  p {
    margin-top: 10px;
    border: 1px solid rgba(211, 156, 50, 1);
  }
  .iconfont {
    font-size: 25px;
    cursor: pointer;
    padding: 3px;
    color: rgba(211, 156, 50);
  }
}
.layers {
  position: absolute;
  width: 80px;
  gap: 5px;
  padding: 8px 5px;
  border: 1px solid rgba(211, 156, 50, 1);
  top: 55%;
  right: 30%;
  display: flex;
  flex-direction: column;
  z-index: 999;
  font-size: 12px;
  color: rgb(15, 161, 214);
  .layer {
    border: 1px solid rgba(211, 156, 50, 1);
    padding: 5px;
    display: flex;
    background-color: rgba(247, 244, 244, 0.2);
  }
  .left {
    width: 10px;
    height: 10px;
    border-width: 1px;
    border-style: solid;
    background-color: white;
  }
  .right {
    margin-left: 12px;
  }
}
.all {
  width: 10px;
  height: 10px;
  border: 1px solid rgba(211, 156, 50, 1);
}
.position {
  position: absolute;
  top: 92.5%;
  left: 20px;
  z-index: 999;
  padding: 5px;
  p {
    font-size: 15px;
    font-weight: 600;
  }
}
:deep(.cesium-viewer) {
  .cesium-viewer-fullscreenContainer {
    position: absolute;
    background-color: transparent !important;
    bottom: 140px;
    right: 537px;
    width: 33px !important;
    height: 33px !important;
    background-color: transparent !important;
    padding: 0;
    overflow: hidden;
    border: 1px solid rgba(211, 156, 50, 1);
    .cesium-fullscreenButton {
      background-color: transparent !important;
      path {
        fill: rgba(211, 156, 50, 1) !important;
      }
    }
  }
  .cesium-timeline-bar {
    position: fixed;
    top: 4px;
    left: 1500px;
    width: 300px;
    height: 30px;
    user-select: none; //禁止选中
  }
}
</style>
